package com.yazi.mxz.gather.main.goods;

import java.io.IOException;
import java.net.SocketException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.yazi.mxz.gather.common.App;
import com.yazi.mxz.gather.common.App.PicObject;
import com.yazi.mxz.gather.entity.enums.ProcessType;
import com.yazi.mxz.gather.entity.http.ZgpfptResBody;
import com.yazi.mxz.gather.entity.http.ZgpfptResBody.Form;
import com.yazi.mxz.gather.entity.repository.ProcessLog;
import com.yazi.mxz.gather.entity.repository.Product;
import com.yazi.mxz.gather.repository.ProcessLogRepository;
import com.yazi.mxz.gather.repository.ProductRepository;

/**
 * 中国批发平台
 * http://www.zgpfpt.com
 * @author mo_yq5
 * @date 2015-8-10
 */
public class ZgpfptCom extends Thread {
	
	CloseableHttpAsyncClient httpclient;
	ProcessLogRepository logRepository;
	ProductRepository productRepository;
	ObjectMapper om;
	
	public ZgpfptCom() {
		
		httpclient = HttpAsyncClients.createDefault();
		httpclient.start();
		
		logRepository = App.context.getBean(ProcessLogRepository.class);
		productRepository = App.context.getBean(ProductRepository.class);
		
		om = new XmlMapper();
		om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	@Override
	public void run() {
		
		ProcessLog log = logRepository.findOne(ProcessType.JGMALL.ordinal());
		if (null == log) {
			log = new ProcessLog();
			log.setId(ProcessType.JGMALL.ordinal());
			log.setCur(13l);// 从小到大(文件名)
			log.setEnd(1l);
			log.setCount(0);
			logRepository.insert(log);
		}
		log.setCur(13l);
		//log.setCount(0);
		
		boolean isContinue = false;
		
		try {
			
			
			while (true) {
				
				if (log.getCur() == 0) {
					isContinue = false;
					break;
				}
				
				barcodeInfo(log.getCur());
				
				log.setCur(log.getCur() - 1);
				logRepository.save(log);
			
				sleep(200);
			}
			
		} catch (SocketException e) {
			e.printStackTrace();
			isContinue = true;
			
		} catch (Exception e1) {
			e1.printStackTrace();
			
		} 
		System.out.println(log.getCur());
		if (isContinue) {
			run();
		} else {
			System.out.println("执行结束！");
		}
	}
	
	private String barcodeInfo(long fileNum) throws JsonParseException, JsonMappingException,
			IOException, InterruptedException, ExecutionException {
		
		System.out.println("fileNum:" + fileNum);
		
		final HttpGet req = new HttpGet("http://localhost/res/test/"+fileNum+".html");
		Future<HttpResponse> future = httpclient.execute(req, null);
		HttpResponse res = future.get();
		
		System.out.println(req.getRequestLine() + "->" + res.getStatusLine());
		
		String body = EntityUtils.toString(res.getEntity(), "gb2312");
		if (body.isEmpty()) {
			System.out.println("无响应内容!");
			return null;
		}
		
		body = "<div>" + body + "</div>";
		
		// 修改结构使能xml解析
		body = body.replaceAll("&nbsp;", "")// 特殊字符
				.replaceAll("&", "")// 特殊字符0141利晨毛巾***
				.replaceAll(" style=\"line-height:0,\"method=\"post\"", "")// 原结构错误
				.replaceAll("<input name=\"imgcode\" type=\"text\" id=\"imgcode\" size=\"6\" />", "")
				.replaceAll("<input name=\"send_btn\" type=\"submit\" value=\"提交修改\">", "")
				.replaceAll("", "")
				.replaceAll("1kg<820ml>厨邦", "厨邦 820ml 1kg")
				.replaceAll("0141利晨毛巾\\*\\*\\*", "利晨毛巾");
		
		//System.out.println(body);
		
		ZgpfptResBody zgpfpt = om.readValue(body, ZgpfptResBody.class);
		List<Form> forms = zgpfpt.getForms();
		StringBuffer goodsInfo;
		String proId, name, barcode, pic, spec, unit, bigPic;
		for (Form form : forms) {
			proId = form.getInputs().get(0).getValue();// 商品Id
			if (proId.isEmpty()) {
				proId = null;
			}
			try {
				bigPic = form.getInputs().get(1).getValue();// 大图片名称
			} catch (Exception e) {
				bigPic = null;
			}
			
			if (bigPic.isEmpty() || bigPic.equals("nophoto.gif")) {
				bigPic = null;
			} else {
				bigPic = "http://www.zgpfpt.com/product/" + bigPic;
			}
			barcode = form.getPs().get(0).getInputs().get(0).getValue();// 条码
			name = form.getPs().get(1).getInputs().get(0).getValue();// 名称
			unit = form.getPs().get(3).getInputs().get(1).getValue();// 单位
			if (unit.isEmpty()) {
				unit = null;
			}
			spec = form.getPs().get(5).getInputs().get(0).getValue();// 规格
			if (spec.isEmpty()) {
				spec = null;
			}
			pic = form.getPs().get(6).getImg().getSrc();// 小图片
			if (pic.isEmpty() || pic.equals("product/small_nophoto.gif")) {
				pic = null;
			} else {
				pic = "http://www.zgpfpt.com/" + pic;
			}
			
			
			if (!App.checkBarCode(barcode)) {
				System.out.println("条码无效: " + proId + " -> " + barcode + " -> "  + name);
				continue;
			}
			
			goodsInfo = new StringBuffer();
			goodsInfo.append("\r\nID:" + proId);
			goodsInfo.append("\r\n条码:" + barcode);
			goodsInfo.append("\r\n名称:" + name);
			goodsInfo.append("\r\n单位:" + unit);
			goodsInfo.append("\r\n规格:" + spec);
			//goodsInfo.append("\r\n单价:" + price);
			//goodsInfo.append("\r\n市场价:" + mkPrice);
			goodsInfo.append("\r\n小图:" + pic);
			goodsInfo.append("\r\n大图:" + bigPic);
			//goodsInfo.append("\r\n地址:" + detailUrl);
			System.out.println(goodsInfo);
			

			App.PicObject picObj = new App.PicObject();
			
			if (null != pic ) {
				App.setPic(pic, picObj);
			}
			if (null != bigPic) {
				App.setPic(bigPic, picObj);
			}
			
			if (!productRepository.exists(barcode)) {
				
				System.out.println("添加: " + barcode + " -> " + name);
				
				if (null != pic && !pic.isEmpty()) {
					pic = App.saveGoodsImage(pic, barcode);
					if (null != pic) {
						App.saveGoodsBigImage(bigPic, pic);
					}
				}

				Product product = new Product();

				//product.setArea(items.getCountry());
				product.setBarcode(barcode);
				product.setBigPic(App.saveGoodsBigImageV1(picObj.getBigPic()));
				//product.setBrandName(brandName);
				//product.setCatName(catName);
				//product.setFacCode(items.getFacCode());
				//product.setFacName(items.getFacName());
				product.setIsCheckName(true);
				product.setMidPic(App.saveGoodsMiddleImageV1(picObj.getMidPic()));
				product.setName(name);
				//product.setSpell(rs.getString("pinyin"));
				product.setPic(App.saveGoodsImageV1(picObj.getPic()));
				//product.setPrice(price);
				product.setUnit(unit);
				product.setSource("zgpfpt.com");
				product.setSpec(spec);
				//product.setSupplier(items.getSupplier());
				product.setSysRemark(proId);

				productRepository.insert(product);

			} else {
				
				System.out.println("修改: " + barcode + " -> " + name);

				Product product = productRepository.findOne(barcode);


				if (null == product.getBigPic()) {
					product.setBigPic(App.saveGoodsBigImageV1(picObj.getBigPic()));
				}
				if (null == product.getMidPic()) {
					product.setMidPic(App.saveGoodsMiddleImageV1(picObj.getMidPic()));
				}
				if (null == product.getPic()) {
					product.setPic(App.saveGoodsImageV1(picObj.getPic()));
				}
				
				if (null != name && null == product.getName()) {
					product.setName(name);
				}
				if (null != unit && null == product.getUnit()) {
					product.setUnit(unit);
				}
				if (null != spec && null == product.getSpec()) {
					product.setSpec(spec);
				}
				
				productRepository.save(product);

			}
			
			sleep(200);
		}
		
		return null;
	}
	
}
